package com.insurance.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.insurance.common.common.ResponseData;
import com.insurance.common.constant.ConstantFlag;
import com.insurance.common.dto.BidSubjectEntityDto;
import com.insurance.common.dto.ProposalCustomerEntityDto;
import com.insurance.common.enums.CommonEnum;
import com.insurance.common.enums.DeleteFlagEnum;
import com.insurance.common.enums.PayTypeEnum;
import com.insurance.common.enums.ResponseEnum;
import com.insurance.common.utils.JwtOperatorUtil;
import com.insurance.entity.OrderEntity;
import com.insurance.entity.ProposalCustomerEntity;
import com.insurance.entity.ProposalEntity;
import com.insurance.enums.OrderStateEnum;
import com.insurance.enums.ProposalCustomerTypeEnum;
import com.insurance.enums.ProposalPersonTypeEnum;
import com.insurance.enums.ProposalStatusEnum;
import com.insurance.pingan.bid.dto.download.DownLoadRequest;
import com.insurance.pingan.bid.dto.download.InvoiceRequest;
import com.insurance.pingan.bid.dto.endorse.EndorseRequest;
import com.insurance.pingan.bid.service.PingAnBidService;
import com.insurance.pingan.bid.utils.PingAnBidRequestUtil;
import com.insurance.product.entity.ProductEntity;
import com.insurance.product.service.ProductService;
import com.insurance.service.OrderService;
import com.insurance.service.ProposalCustomerService;
import com.insurance.service.ProposalService;
import com.insurance.service.entity.BidBillEntity;
import com.insurance.service.entity.BidSubjectEntity;
import com.insurance.service.enums.BidSubjectCorrectingStateEnum;
import com.insurance.service.enums.BidSubjectStateEnum;
import com.insurance.service.service.BidBillService;
import com.insurance.service.service.BidInvoiceService;
import com.insurance.service.service.BidSubjectService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.lang.System.out;

/**
 * 投标控制器
 * @version 1.0
 * @date 2020/10/11
 **/
@Slf4j
@RestController
@RequestMapping("/api/bid")
public class ApiBidController {

    //region 类注入
    /**
     * 投标service
     */
    @Autowired
    private BidSubjectService bidSubjectService;

    /**
     * 发票service
     */
    @Autowired
    private BidInvoiceService bidInvoiceService;

    /**
     * 产品service
     */
    @Autowired
    private ProductService productService;

    /**
     * 投保单service
     */
    @Autowired
    private ProposalService proposalService;

    /**
     * 订单service
     */
    @Autowired
    private OrderService orderService;

    /**
     * 投被保险人service
     */
    @Autowired
    private ProposalCustomerService proposalCustomerService;

    /**
     * 平安投保service
     */
    @Autowired
    private PingAnBidService pingAnBidService;

    /**
     * 发票service
     */
    @Autowired
    private BidBillService bidBillService;

    /**
     * 日期格式化
     */
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    //endregion

    //region 保存投标信息

    /**
     * 保存投标信息
     *
     * @param bidSubjectEntity 投标实体类
     * @return
     */
    @PostMapping("/saveSubject")
    public ResponseData saveSubject(HttpServletRequest request, BidSubjectEntity bidSubjectEntity, String proposalCustomerListStr){
        try {
            JSONArray proposalCustomerJsonArray = JSONArray.fromObject(proposalCustomerListStr);
            List<ProposalCustomerEntity> proposalCustomerEntityList = JSONArray.toList(proposalCustomerJsonArray, ProposalCustomerEntity.class);
            ProposalEntity proposalEntity = null;
            try {
                //获取token
//                String token = request.getAttribute("Authorization").toString();
                String token = request.getHeader("Authorization");
                //获取投保单对象
                proposalEntity = convertProposal(token);
            } catch (Exception e) {
                log.error("【组装投保单对象异常】", e);
            }
            for (int i = 0; i < proposalCustomerEntityList.size(); i++) {
                ProposalCustomerEntity proposalCustomerEntity = proposalCustomerEntityList.get(i);
                proposalCustomerEntity.setProductId(proposalEntity.getProductId());
                proposalCustomerEntity.setProposalNo(proposalEntity.getProposalNo());
                proposalCustomerEntity.setPersonType(ProposalPersonTypeEnum.ENTERPRISE.getCode());
                proposalCustomerEntity.setCreateTime(new Date());
                if(i == 0){
                    proposalCustomerEntity.setCustomerType(ProposalCustomerTypeEnum.INSURE.getCode());
                }else if(i == 1){
                    proposalCustomerEntity.setCustomerType(ProposalCustomerTypeEnum.BEINSURE.getCode());
                }
            }
            bidSubjectEntity.setInsuranceStartTime(sdf.format(new Date()));
            bidSubjectEntity.setCreateTime(new Date());
            //保存状态
            bidSubjectEntity.setState(BidSubjectStateEnum.SAVE.getMessage());
            //未批改状态
            bidSubjectEntity.setCorrectingState(BidSubjectCorrectingStateEnum.IS_NOT_CORRECTING.getCode());
            if(bidSubjectService.saveSubjectAndCustomers(bidSubjectEntity, proposalEntity, proposalCustomerEntityList)){
                return ResponseData.success(CommonEnum.OPERATION_SUCCESS, bidSubjectEntity.getSubjectId().toString());
            }else{
                log.error("【保存投标信息失败】");
                return ResponseData.error(CommonEnum.OPERATION_ERROR);
            }
        } catch (Exception e) {
            log.error("【保存投标信息失败, 系统异常】", e);
            return ResponseData.error(ResponseEnum.SYSTEM_ERROR);
        }
    }
    //endregion

    //region 组装投保单对象

    /**
     * 组装投保单对象
     *
     * @param token
     * @return
     */
    public ProposalEntity convertProposal(String token){
        //获取投标保证保险
        ProductEntity productEntity = productService.getById(1L);
        ProposalEntity proposalEntity = new ProposalEntity();
        proposalEntity.setProposalNo("P_TBBZBX_"+ IdUtil.fastSimpleUUID());
        proposalEntity.setProductId("1");
        proposalEntity.setProductName(productEntity.getProductName());
        proposalEntity.setInsuranceCompany(productEntity.getInsureName());
        proposalEntity.setCreatePersonId(JwtOperatorUtil.getUserId(token));
        proposalEntity.setCreatePersonName(JwtOperatorUtil.getUserName(token));
        proposalEntity.setTelephone(JwtOperatorUtil.getTelephone(token));
        proposalEntity.setIdCard(JwtOperatorUtil.getCardId(token));
        proposalEntity.setCreateTime(new Date());
        proposalEntity.setTotalPrice("2000");
        proposalEntity.setTotalInsuranceAmount("200000");
        proposalEntity.setAppId(JwtOperatorUtil.getAppId(token));
        proposalEntity.setState(ProposalStatusEnum.SAVE.getCode());
        proposalEntity.setDeleteFlag(String.valueOf(DeleteFlagEnum.UN_DELETE.getCode()));
        return proposalEntity;
    }
    //endregion

    //region 预支付下单

    /**
     * 预支付下单
     *
     * @param subjectId
     * @return
     */
    @PostMapping("/{subjectId}/prePayFinance")
    public ResponseData prePayFinance(HttpServletRequest request, @PathVariable String subjectId){
        try {
            BidSubjectEntity bidSubjectEntity = bidSubjectService.getById(subjectId);
            if(bidSubjectEntity == null){
                return ResponseData.error(CommonEnum.QUERY_ERROR_NODATA);
            }
            String token = JwtOperatorUtil.getToken(request);
            ProposalEntity proposalEntity = proposalService.getById(bidSubjectEntity.getProposalId());
            OrderEntity orderEntity = convertOrder(token, proposalEntity);
            orderEntity.setOrderPrice(bidSubjectEntity.getTotalActualPremium());
            //调用平安预支付下单接口
            String callUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/api/bid/"+bidSubjectEntity.getSubjectId()+"/acceptForFee";
            log.info("【支付确认回调地址：{}】", callUrl);
            JSONObject jsonObject = bidSubjectService.prePayFinance(callUrl, subjectId, orderEntity);
            if(ConstantFlag.SUCCESS.equals(jsonObject.getString(ConstantFlag.CODE))){
                return ResponseData.success(jsonObject);
            }else{
                log.error("【预支付下单失败, 接口调用失败】");
            }
        } catch (Exception e) {
            log.error("【预支付下单失败, 系统异常】", e);
        }
        return ResponseData.error(CommonEnum.OPERATION_ERROR);

    }
    //endregion

    //region 创建订单

    /**
     * 创建订单
     *
     * @param token
     * @param proposalEntity
     * @return
     */
    public OrderEntity convertOrder(String token, ProposalEntity proposalEntity){
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderNo("O_TBBZBX_"+ IdUtil.fastSimpleUUID());
        orderEntity.setProposalId(proposalEntity.getProposalId());
        orderEntity.setProposalNo(proposalEntity.getProposalNo());
        orderEntity.setProductId(proposalEntity.getProductId());
        orderEntity.setProductName(proposalEntity.getProductName());
        orderEntity.setCreatePersonId(JwtOperatorUtil.getUserId(token));
        orderEntity.setCreateTime(new Date());
        orderEntity.setTelephone(JwtOperatorUtil.getTelephone(token));
        orderEntity.setCardId(JwtOperatorUtil.getCardId(token));
        orderEntity.setPayType(PayTypeEnum.PINGAN.getCode());
        orderEntity.setOrderState(OrderStateEnum.NO_PAY.getCode());
        return orderEntity;
    }
    //endregion

    //region 查询投标详情

    /**
     * 查询投标详情
     *
     * @param subjectId 投标主键
     * @return
     */
    @PostMapping("/{subjectId}/querySubjectDetail")
    public ResponseData querySubjectDetail(@PathVariable String subjectId){
        try {
            //通过主键查询投标详情
            BidSubjectEntity bidSubjectEntity = bidSubjectService.getById(subjectId);
            //通过投保单主键查询投保单对象
            ProposalEntity proposalEntity = proposalService.getById(bidSubjectEntity.getProposalId());
            //通过投保单主键查询投被保险人
            List<ProposalCustomerEntity> proposalCustomerEntityList = proposalCustomerService.findByProposalId(bidSubjectEntity.getProposalId());
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("bidSubject", bidSubjectEntity);
            resultMap.put("proposal", proposalEntity);
            for (ProposalCustomerEntity proposalCustomerEntity : proposalCustomerEntityList){
                //投保人
                if(ProposalCustomerTypeEnum.INSURE.getCode().equals(proposalCustomerEntity.getCustomerType())){
                    resultMap.put("applicantCustomer", proposalCustomerEntity);
                }
                //被保险人
                if(ProposalCustomerTypeEnum.BEINSURE.getCode().equals(proposalCustomerEntity.getCustomerType())){
                    resultMap.put("insurantCustomer", proposalCustomerEntity);
                }
            }
            return ResponseData.success(resultMap);
        } catch (Exception e) {
            log.error("【查询投标详情失败, 系统异常】", e);
            return ResponseData.error(CommonEnum.SYSTEM_ERROR);
        }
    }
    //endregion

    //region 平安主动查询投保信息

    /**
     * 平安主动查询投保信息
     *
     * @param subjectId 投标信息主键
     * @return
     */
    @RequestMapping("/{subjectId}/acceptForFee")
    public void acceptForFee(HttpServletResponse response, @PathVariable String subjectId){
        try {
            JSONObject jsonObject = bidSubjectService.acceptForFee(subjectId);
//            return ResponseData.success(CommonEnum.OPERATION_SUCCESS);
//            response.sendRedirect("http://localhost:8001/#/ordersuccess");
            response.sendRedirect("http://39.98.148.165/insurance-bid-vue/#/ordersuccess");
        } catch (Exception e) {
            log.error("【平安主动查询投保信息失败, 系统异常】", e);
//            return ResponseData.success(CommonEnum.OPERATION_ERROR);
            try {
//                response.sendRedirect("http://localhost:8001/#/ordererror");
                response.sendRedirect("http://39.98.148.165/insurance-bid-vue/#/ordererror");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    //endregion

    //region 查询订单信息

    /**
     * 查询订单信息
     *
     * @param subjectId 投标信息主键
     * @return
     */
    @PostMapping("/{subjectId}/queryOrderInfo")
    public ResponseData queryOrderInfo(@PathVariable String subjectId){
        BidSubjectEntity bidSubjectEntity = bidSubjectService.getById(subjectId);
        if(bidSubjectEntity == null){
            return ResponseData.error(CommonEnum.QUERY_ERROR_NODATA);
        }
        OrderEntity orderEntity = orderService.getById(bidSubjectEntity.getOrderId());
        if(orderEntity == null){
            return ResponseData.error(CommonEnum.QUERY_ERROR_NODATA);
        }
        if(OrderStateEnum.COMPLETE.getCode().equals(orderEntity.getOrderState())){
            return ResponseData.success(CommonEnum.OPERATION_SUCCESS);
        }
        return ResponseData.success(CommonEnum.OPERATION_ERROR);
    }
    //endregion

    //region 查询投保单列表

    /**
     * 查询投保单列表
     *
     * @param request 请求
     * @param page 分页
     * @param productName 产品名称
     * @param state 状态
     * @return
     */
    @PostMapping("/queryProposalPage")
    public ResponseData queryProposalPage(HttpServletRequest request, Page page, String productName, String state){
        String userId = JwtOperatorUtil.getUserId(request);
        Page<ProposalEntity> proposalEntityPage = proposalService.findByUserId(page, userId, productName, state);
        List<ProposalEntity> proposalEntityList = proposalEntityPage.getRecords();
        if(CollectionUtils.isNotEmpty(proposalEntityList)){
            for(ProposalEntity proposalEntity : proposalEntityList){
                BidSubjectEntity bidSubjectEntity = bidSubjectService.getByProposalId(proposalEntity.getProposalId());
                if(bidSubjectEntity != null){
                    proposalEntity.setOnlineUrl(String.valueOf(bidSubjectEntity.getSubjectId()));
                }
            }
        }
        return ResponseData.success(proposalEntityPage);
    }
    //endregion

    //region 分页查询订单

    /**
     * 分页查询订单
     *
     * @param request
     * @param page
     * @return
     */
    @PostMapping("/queryOrderPage")
    public ResponseData queryOrderPage(HttpServletRequest request, Page page){
        //获取当前用户主键
        String userId = JwtOperatorUtil.getUserId(request);
        //分页查询
        Page<OrderEntity> orderEntityPage = orderService.findByUserIdPage(page, userId);
        //获取列表数据
        List<OrderEntity> records = orderEntityPage.getRecords();
        //循环设置信息
        for (OrderEntity orderEntity : records){
            try {
                //通过投保单主键查询投保单
                ProposalEntity proposalEntity = proposalService.getById(orderEntity.getProposalId());
                //通过投保单主键查询投被保险人对象
                List<ProposalCustomerEntity> customerList = proposalCustomerService.findByProposalId(orderEntity.getProposalId());
                orderEntity.setInsuraceNo(proposalEntity.getInsuranceNo());
                orderEntity.setApplicationCustomerName(customerList.get(0).getCustomerName());
                orderEntity.setInsuranceCompany(proposalEntity.getInsuranceCompany());
                //通过投保单主键查询投标主表对象
                BidSubjectEntity bidSubjectEntity = bidSubjectService.getByProposalId(orderEntity.getProposalId());
                orderEntity.setSubjectIdText(String.valueOf(bidSubjectEntity.getSubjectId()));
                //通过订单id查询发票信息对象
                BidBillEntity bidBillEntity = bidBillService.queryByOrderId(orderEntity.getOrderId());
                orderEntity.setIsPrintInvoice(bidBillEntity != null ? "1" : "0");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResponseData.success(orderEntityPage);
    }
    //endregion

    //region 查询订单详情

    /**
     * 查询订单详情
     *
     * @param orderId
     * @return
     */
    @PostMapping("/{orderId}/queryOrderDetail")
    public ResponseData queryOrderDetail(@PathVariable String orderId){
        OrderEntity orderEntity = orderService.getById(orderId);
        try {
            //通过投保单主键查询投保单对象
            ProposalEntity proposalEntity = proposalService.getById(orderEntity.getProposalId());
            //查询投被保险人
            List<ProposalCustomerEntity> customerList = proposalCustomerService.findByProposalId(orderEntity.getProposalId());
            orderEntity.setInsuraceNo(proposalEntity.getInsuranceNo());
            orderEntity.setApplicationCustomerName(customerList.get(0).getCustomerName());
            orderEntity.setInsuranceCompany(proposalEntity.getInsuranceCompany());
            //通过订单主键查询发票信息对象
            BidBillEntity bidBillEntity = bidBillService.queryByOrderId(orderEntity.getOrderId());
            //不为空就是已经开具发票
            orderEntity.setIsPrintInvoice(bidBillEntity != null ? "1" : "0");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseData.success(orderEntity);
    }
    //endregion

    //region 取消订单

    /**
     * 取消订单
     *
     * @param orderId 订单主键
     * @return
     */
    @PostMapping("{orderId}/cancelOrder")
    @ResponseBody
    public ResponseData cancelOrder(@PathVariable String orderId){
        //通过订单主键查询订单
        OrderEntity order = orderService.getById(orderId);
        if(order == null){
            return ResponseData.error(CommonEnum.OPERATION_ERROR);
        }
        order.setOrderState(OrderStateEnum.CANCEL.getCode());
        boolean flag = orderService.updateById(order);
        return flag ? ResponseData.success(CommonEnum.OPERATION_SUCCESS) : ResponseData.error(CommonEnum.OPERATION_ERROR);
    }
    //endregion

    //region 查询投保单详情

    /**
     * 查询投保单详情
     *
     * @param proposalId 投保单主键
     * @return
     */
    @PostMapping("/{proposalId}/queryProposalDetail")
    public ResponseData queryProposalDetail(@PathVariable String proposalId){
        try {
            ProposalEntity proposalEntity = proposalService.getById(proposalId);
            BidSubjectEntity bidSubjectEntity = bidSubjectService.getByProposalId(proposalId);
            List<ProposalCustomerEntity> customerList = proposalCustomerService.findByProposalId(proposalId);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("proposal", proposalEntity);
            resultMap.put("bidSubject", bidSubjectEntity);
            resultMap.put("applicantCustomer", customerList.get(0));
            resultMap.put("insurantCustomer", customerList.get(1));
            return ResponseData.success(resultMap);
        } catch (Exception e) {
            log.error("【查询投保单详情失败】", e);
            return ResponseData.error(CommonEnum.QUERY_ERROR);
        }
    }
    //endregion

    //region 下载平安电子保单

    /**
     * 下载平安电子保单
     *
     * @param out
     * @param proposalId
     */
    @GetMapping("/{proposalId}/downLoadPDF")
    public void downLoadPDF(OutputStream out, @PathVariable String proposalId){
        try {
            BidSubjectEntity bidSubjectEntity = bidSubjectService.getByProposalId(proposalId);
            BidSubjectEntityDto bidSubjectEntityDto = new BidSubjectEntityDto();
            BeanUtils.copyProperties(bidSubjectEntity, bidSubjectEntityDto);
            DownLoadRequest downLoadRequest = PingAnBidRequestUtil.createDownLoadRequest(bidSubjectEntityDto);
            String result = pingAnBidService.printGP(JSONObject.fromObject(downLoadRequest).toString());
            JSONObject resultJson = JSONObject.fromObject(result);
            //表示成功
            if(resultJson.getString("ret").equals("0")){
                JSONObject dataJson = resultJson.getJSONObject("data");
                if(dataJson.getString("responseCode").equals("999999") && dataJson.containsKey("returnPdfValue")){
                    String pdfBase64 = dataJson.getString("returnPdfValue");
                    byte[] content = Base64.getDecoder().decode(pdfBase64);
                    IoUtil.write(out, false, content);
                }else{
                    throw new Exception("【调用平安电子保单接口异常】");
                }
            }else{
                throw new Exception("【调用平安电子保单接口异常, 返回错误】");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //endregion

    //region 保存发票信息并打印(响应发票信息字节数组)

    /**
     * 保存发票信息并打印(响应发票信息字节数组)
     *
     * @param request
     * @param response
     * @param bidBillEntity
     * @param proposalId
     * @param orderId
     * @param taxPayerNO
     * @throws IOException
     */
    @GetMapping("/{proposalId}/{orderId}/printInvoice")
    public void printInvoice(HttpServletRequest request, HttpServletResponse response, BidBillEntity bidBillEntity, @PathVariable String proposalId, @PathVariable String orderId, String taxPayerNO) throws IOException {
        OutputStream out = null;
        try {
            //校验是否可以开发票
            //通过投保单主键查询发票对象
            BidBillEntity bbe = bidBillService.queryByProposalId(proposalId);
            if(bbe != null){
                //设置response使用utf-8码表，以控制response以什么码表向浏览器写出数据
                response.setCharacterEncoding("UTF-8");
                //指定浏览器以什么码表打开服务器发送的数据
                response.setContentType("text/html;charset=utf-8");
                out = response.getOutputStream();
                out.write("开具发票失败, 不能重复申请开具发票".getBytes());
            }else{
                //通过投保单主键查询投标对象
                BidSubjectEntity bidSubjectEntity = bidSubjectService.getByProposalId(proposalId);
                bidBillEntity.setOrderId(orderId);
                bidBillEntity.setSubjectId(bidSubjectEntity.getSubjectId());
                bidBillEntity.setProposalId(proposalId);
                bidBillEntity.setCreatePersonId(JwtOperatorUtil.getUserId(request));
                bidBillEntity.setCreateTime(new Date());

                //通过投保单主键查询投保单对象
                ProposalEntity proposalEntity = proposalService.getById(proposalId);
                //通过投保单对象查询投保人
                ProposalCustomerEntity proposalCustomerEntity = proposalCustomerService.findByProposalId(proposalId).get(0);
                //转换投保人对象为Dto对象
                ProposalCustomerEntityDto proposalCustomerEntityDto = new ProposalCustomerEntityDto();
                BeanUtils.copyProperties(proposalCustomerEntity, proposalCustomerEntityDto);
                //保存发票信息并打印(返回发票信息字节数组)
                byte[] content = bidBillService.saveAndPrintInvoice(bidBillEntity, taxPayerNO, proposalEntity, proposalCustomerEntityDto);
                if(content == null || content.length < 1){
                    //设置response使用utf-8码表，以控制response以什么码表向浏览器写出数据
                    response.setCharacterEncoding("UTF-8");
                    //指定浏览器以什么码表打开服务器发送的数据
                    response.setContentType("text/html;charset=utf-8");
                    out = response.getOutputStream();
                    out.write("开具发票失败".getBytes("UTF-8"));
                }else{
                    out = response.getOutputStream();
                    IoUtil.write(out, false, content);
                }
            }
        } catch (Exception e) {
            log.error("【开具发票失败, 系统异常】", e);
            //设置response使用utf-8码表，以控制response以什么码表向浏览器写出数据
            response.setCharacterEncoding("UTF-8");
            //指定浏览器以什么码表打开服务器发送的数据
            response.setContentType("text/html;charset=utf-8");
            out = response.getOutputStream();
            out.write("开具发票失败".getBytes("UTF-8"));
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //endregion

    @PostMapping("{proposalId}/endorse")
    public ResponseData endorse(@PathVariable String proposalId){
        try {
            //通过投保单主键查询标的对象
            BidSubjectEntity bidSubjectEntity = bidSubjectService.getByProposalId(proposalId);
            log.info("【批改标的信息, subjectId：{}】", bidSubjectEntity.getSubjectId());
            BidSubjectEntityDto bidSubjectEntityDto = new BidSubjectEntityDto();
            BeanUtils.copyProperties(bidSubjectEntity, bidSubjectEntityDto);
            //投保人
            ProposalCustomerEntity applicationCustomer = proposalCustomerService.findApplicationCustomer(proposalId);
            //被保人
            ProposalCustomerEntity insuredCustomer = proposalCustomerService.findInsuredCustomer(proposalId);
            //投保人dto
            ProposalCustomerEntityDto applicationCustomerDto = new ProposalCustomerEntityDto();
            BeanUtils.copyProperties(applicationCustomer, applicationCustomerDto);
            //被保人dto
            ProposalCustomerEntityDto insuredCustomerDto = new ProposalCustomerEntityDto();
            BeanUtils.copyProperties(insuredCustomer, insuredCustomerDto);
            //组装批改对象
            EndorseRequest endorseRequest = PingAnBidRequestUtil.createEndorseRequest(bidSubjectEntityDto, applicationCustomerDto, insuredCustomerDto);

            JSONObject endorseRequestJSON = JSONObject.fromObject(endorseRequest);
            //调用批改接口
            String resultStr = pingAnBidService.edrSceneCode(endorseRequestJSON.toString());
            JSONObject resultJson = PingAnBidRequestUtil.pingAnEndorseValidate(resultStr);
            //如果批改成功
            if(resultJson.containsKey(ConstantFlag.CODE) && ConstantFlag.SUCCESS.equals(resultJson.get(ConstantFlag.CODE))){
                bidSubjectEntity.setEndorseApplyNo(resultJson.getString("endorseApplyNo"));
                bidSubjectEntity.setEndorseNo(resultJson.getString("endorseNo"));
                bidSubjectEntity.setCorrectingState(BidSubjectCorrectingStateEnum.IS_CORRECTING.getCode());
                bidSubjectEntity.setUpdateTime(new Date());
                boolean flag = bidSubjectService.updateById(bidSubjectEntity);
                if(flag){
                    log.info("【批改成功, proposalId: {}】", proposalId);
                    log.info("【批改成功, subjectId: {}】", bidSubjectEntity.getSubjectId());
                    return ResponseData.success(CommonEnum.OPERATION_SUCCESS);
                }else{
                    log.info("【批改成功, 修改标的信息失败, proposalId: {}】", proposalId);
                    log.info("【批改成功, 修改标的信息失败, subjectId: {}】", bidSubjectEntity.getSubjectId());
                }
            }
            log.error("【批改失败, proposalId: {}】", proposalId);
            log.error("【批改失败, subjectId: {}】", bidSubjectEntity.getSubjectId());
            return ResponseData.success(CommonEnum.OPERATION_ERROR);
        } catch (Exception e) {
            log.error("【批改失败, proposalId: {}, 系统异常：{}】", proposalId, e.getMessage());
            return ResponseData.success(CommonEnum.OPERATION_ERROR);
        }
    }


    @RequestMapping("/payBack")
    public ResponseData payBack(HttpServletRequest request){
        log.info("【进入回调...】");
        Map<String, String[]> parameterMap = request.getParameterMap();
        log.info(JSONObject.fromObject(parameterMap).toString());
        return ResponseData.success();
    }

}
